package com.conversationboard.dns;

import java.io.IOException;

import org.xbill.DNS.DClass;
import org.xbill.DNS.ExtendedResolver;
import org.xbill.DNS.Message;
import org.xbill.DNS.Name;
import org.xbill.DNS.Record;
import org.xbill.DNS.Resolver;
import org.xbill.DNS.ReverseMap;
import org.xbill.DNS.Section;
import org.xbill.DNS.Type;

public class DNS {

	public static String dnsLoopup(String ipAddress) throws IOException {

		Resolver resolver = new ExtendedResolver();

		Name name = ReverseMap.fromAddress(ipAddress);
		int type = Type.PTR;
		int dnsClass = DClass.IN;
		Record rec = Record.newRecord(name, type, dnsClass);
		Message query = Message.newQuery(rec);
		Message response = resolver.send(query);

		Record[] answers = response.getSectionArray(Section.ANSWER);

		if (answers.length == 0) {
			return ipAddress;
		} else {
			return answers[0].rdataToString();
		}
	}

}
